package com.jnxx.task.WxUtils;


import com.alibaba.fastjson.JSONObject;
import com.jnxx.basic.util.HttpTool;
import com.jnxx.task.WxVo.AccessTokenResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class TokenUtils {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RestTemplate restTemplate;

    private final String corpId = "ww4009210d5c2665df";
    private final String secret = "MdazgK3RX3HcC_bmwORn9lnfPcoK6wz85a9hLpZjYt0";

    public String getAccessToken() {
        String accessToken = stringRedisTemplate.opsForValue().get("accessToken");
        if (accessToken == null) {
            String url = String.format("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s", corpId, secret);
            ResponseEntity<AccessTokenResponse> response = restTemplate.getForEntity(url, AccessTokenResponse.class);
            // accessToken = Objects.requireNonNull(response.getBody()).getAccess_token();
            accessToken = response.getBody().getAccess_token();
            stringRedisTemplate.opsForValue().set("accessToken", accessToken, 6900, TimeUnit.SECONDS);
        }
        return accessToken;
    }
    // 获取企业的 jsapi_ticket
    public String getJsapiTicket(){
        try {
            String accessToken = getAccessToken();
            String urlTmp = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=%s";

            String url = String.format(urlTmp, accessToken);

            String res = HttpTool.sendGetNoParams(url);
            JSONObject jsonObject = JSONObject.parseObject(res);
            String errmsg = jsonObject.getString("errmsg");
            if (!"ok".equals(errmsg)){
                log.error("获取企业jsapi_ticket错误：" + errmsg);
                return "false";
            }
            String jsapiTicket = jsonObject.getString("ticket");
            // 存入7200秒
            stringRedisTemplate.opsForValue().set("jsapiTicket", jsapiTicket, 7200, TimeUnit.SECONDS);
            return res;
        } catch (Exception e) {
            log.error("获取企业jsapi_ticket错误");
            throw new RuntimeException(e);
        }
    }

}
